package com.iotechn.unimall.biz.service.distribution;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.iotechn.unimall.biz.service.config.ConfigBizService;
import com.iotechn.unimall.core.Const;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.*;
import com.iotechn.unimall.data.dto.DistributionOrderDTO;
import com.iotechn.unimall.data.dto.DistributionRankingDTO;
import com.iotechn.unimall.data.dto.DistributionUserDTO;
import com.iotechn.unimall.data.enums.DistributionDeductionStatusType;
import com.iotechn.unimall.data.enums.DistributionStrategyMergeType;
import com.iotechn.unimall.data.enums.DistributionStrategyType;
import com.iotechn.unimall.data.mapper.*;
import com.iotechn.unimall.data.model.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/11/28
 * Time: 14:20
 */
@Service
public class DistributionBizService {

    @Autowired
    private DistributionMapper distributionMapper;

    @Autowired
    private DistributionBalanceDetailMapper distributionBalanceDetailMapper;

    @Autowired
    private DistributionStrategyMapper distributionStrategyMapper;

    @Autowired
    private DistributionDeductionMapper distributionDeductionMapper;

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CacheComponent cacheComponent;

    @Autowired
    private ConfigBizService configBizService;

    public static final String CA_DISTRIBUTION_STRATEGY_SPU = "CA_DISTRIBUTION_STRATEGY_SPU_";

    public void distribute(OrderDO order, OrderSkuDO item) {
        DistributionStrategyDO strategy = this.getSpuStrategy(item.getSpuId());
        if (strategy != null) {
            //获取到策略
            Long distributionId = order.getDistributionId();
            DistributionDO distributionDO = distributionMapper.selectById(distributionId);
            int radio = strategy.getRadio();
            UserDO userDO = userMapper.selectById(distributionDO.getUserId());
            Integer groupMaster = userDO.getGroupMaster();
          /*  if (groupMaster == 1) {
                Integer groupMasterRadio = configBizService.getMerchantConfig().getGroupMasterRadio() == null ? 0 : configBizService.getMerchantConfig().getGroupMasterRadio();
                radio = radio * (100 + groupMasterRadio) / 100;
            }*/
            int skuTotalPrice = item.getPrice() * item.getNum();
            if (distributionDO.getLevel() == 3) {
                long secondId = this.incFreezeBalance(skuTotalPrice * radio * strategy.getThirdRadio() / 1000000,
                        distributionDO.getId(), order.getOrderNo(), item.getSpuTitle() + "-" + item.getTitle() + "-冻结佣金");
                if (secondId > 0) {
                    long firstId = this.incFreezeBalance(skuTotalPrice * radio * strategy.getSecondRadio() / 1000000,
                            secondId, order.getOrderNo(), item.getSpuTitle() + "-" + item.getTitle() + "-冻结佣金");
                    if (firstId > 0) {
                        this.incFreezeBalance(skuTotalPrice * radio * strategy.getFirstRadio() / 1000000,
                                firstId, order.getOrderNo(), item.getSpuTitle() + "-" + item.getTitle() + "-冻结佣金");
                    }
                }
            } else if (distributionDO.getLevel() == 2) {
                // 首先判断 上级销售策略
                int realSecondRadio;
                if (strategy.getMergeType() == DistributionStrategyMergeType.SUPERPOSITION.getCode()) {
                    realSecondRadio = strategy.getSecondRadio() + strategy.getThirdRadio();
                } else {
                    realSecondRadio = strategy.getSecondRadio() > strategy.getThirdRadio() ? strategy.getSecondRadio() : strategy.getThirdRadio();
                }
                long firstId = this.incFreezeBalance(skuTotalPrice * radio * realSecondRadio / 1000000,
                        distributionDO.getId(), order.getOrderNo(), item.getSpuTitle() + "-" + item.getTitle() + "-冻结佣金");
                if (firstId > 0) {
                    this.incFreezeBalance(skuTotalPrice * radio * strategy.getFirstRadio() / 1000000,
                            firstId, order.getOrderNo(), item.getSpuTitle() + "-" + item.getTitle() + "-冻结佣金");
                }
            } else if (distributionDO.getLevel() == 1) {
                int realFirstRadio;
                if (strategy.getMergeType() == DistributionStrategyMergeType.SUPERPOSITION.getCode()) {
                    realFirstRadio = strategy.getFirstRadio() + strategy.getSecondRadio() + strategy.getThirdRadio();
                } else {
                    realFirstRadio = strategy.getFirstRadio() > strategy.getSecondRadio() ? strategy.getFirstRadio() : (strategy.getSecondRadio() > strategy.getThirdRadio() ? strategy.getSecondRadio() : strategy.getThirdRadio());
                }
                this.incFreezeBalance(skuTotalPrice * radio * realFirstRadio / 1000000,
                        distributionDO.getId(), order.getOrderNo(), item.getSpuTitle() + "-" + item.getTitle() + "-冻结佣金");
            }
        }
    }

    public void distribute(OrderDO order) {
            //获取到策略
            Long distributionId = order.getDistributionId();
            DistributionDO distributionDO = distributionMapper.selectById(distributionId);
            //UserDO userDO = userMapper.selectById(distributionDO.getUserId());
            this.incFreezeBalance(order.getActualPrice(),
                        distributionDO.getId(), order.getOrderNo(), order.getOrderNo()  + "-冻结佣金");


    }


    /**
     * 获取商品策略
     *
     * @param spuId
     * @return
     */
    private DistributionStrategyDO getSpuStrategy(Long spuId) {
        DistributionStrategyDO distributionStrategyDO = cacheComponent.getObj(CA_DISTRIBUTION_STRATEGY_SPU + spuId, DistributionStrategyDO.class);
        if (distributionStrategyDO == null) {
            //step1.1. 查询SPU策略
            List<DistributionStrategyDO> strategySpuList = distributionStrategyMapper
                    .selectList(new EntityWrapper<DistributionStrategyDO>()
                            .eq("type_id", spuId)
                            .eq("type", DistributionStrategyType.GOODS.getCode()));
            if (CollectionUtils.isEmpty(strategySpuList)) {
                //step2.1. 查询Category策略
                SpuDO spuDO = spuMapper.selectById(spuId);
                Long categoryId = spuDO.getCategoryId();
                List<DistributionStrategyDO> strategyCategoryList = distributionStrategyMapper
                        .selectList(new EntityWrapper<DistributionStrategyDO>()
                                .eq("type_id", categoryId)
                                .eq("type", DistributionStrategyType.CATEGORY.getCode()));
                if (CollectionUtils.isEmpty(strategyCategoryList)) {
                    //step3.1. 查询全部策略
                    List<DistributionStrategyDO> strategyAllList = distributionStrategyMapper
                            .selectList(new EntityWrapper<DistributionStrategyDO>()
                                    .eq("type_id", 0)
                                    .eq("type", DistributionStrategyType.ALL.getCode()));
                    if (CollectionUtils.isEmpty(strategyAllList)) {
                        DistributionStrategyDO noneDO = new DistributionStrategyDO();
                        noneDO.setType(DistributionStrategyType.CACHE_NONE.getCode());
                        cacheComponent.putObj(CA_DISTRIBUTION_STRATEGY_SPU + spuId, noneDO, Const.CACHE_ONE_DAY);
                        return null;
                    } else {
                        //step3.2. 使用全部策略
                        cacheComponent.putObj(CA_DISTRIBUTION_STRATEGY_SPU + spuId, strategyAllList.get(0), Const.CACHE_ONE_DAY);
                        return strategyAllList.get(0);
                    }
                } else {
                    //step2.2 使用Category策略
                    cacheComponent.putObj(CA_DISTRIBUTION_STRATEGY_SPU + spuId, strategyCategoryList.get(0), Const.CACHE_ONE_DAY);
                    return strategyCategoryList.get(0);
                }
            } else {
                //1.2. 使用SPU策略
                cacheComponent.putObj(CA_DISTRIBUTION_STRATEGY_SPU + spuId, strategySpuList.get(0), Const.CACHE_ONE_DAY);
                return strategySpuList.get(0);
            }
        } else {
            if (distributionStrategyDO.getType() == DistributionStrategyType.CACHE_NONE.getCode()) {
                return null;
            } else {
                return distributionStrategyDO;
            }
        }
    }


    /**
     * 增加分销者 冻结余额
     *
     * @param delta
     * @param distributionId
     * @param orderNo
     * @param description
     * @return 返回 parentId
     */
    public long incFreezeBalance(Integer delta, Long distributionId, String orderNo, String description) {
        //将 Distribution 表 和 明细表查出，并加上行锁。此处必须同时拿到余额表的行锁 与 余额明细表的行锁。
        Date now = new Date();
        DistributionDO distributionDO = distributionMapper.selectByIdForUpdate(distributionId);
        if (distributionDO != null) {
            DistributionBalanceDetailDO lastDetailDO = distributionBalanceDetailMapper.getDistributionUserLastForUpdate(distributionId);
            if (lastDetailDO == null) {
                // 未产生明细，则余额为0
                lastDetailDO = new DistributionBalanceDetailDO();
                lastDetailDO.setBalance(0);
                lastDetailDO.setFreezeBalance(0);
            }
            //校验明细表与余额表是否数据一致
            if (!lastDetailDO.getFreezeBalance().equals(distributionDO.getFreezeBalance()) || !lastDetailDO.getBalance().equals(distributionDO.getBalance())) {
                // 出现数据不一致的情况。  不再对此用户进行分销提成。 未有人工干预，理论上绝对一致
            } else {
                //更新操作
                if (delta != 0) {
                    //更新主表
                    distributionMapper.incFreezeBalance(distributionId, delta);
                    //更新明细表
                    DistributionBalanceDetailDO balanceDetailDO = new DistributionBalanceDetailDO();
                    balanceDetailDO.setFreezeBalance(distributionDO.getFreezeBalance() + delta);
                    balanceDetailDO.setFreezeBalanceDelta(delta);
                    balanceDetailDO.setBalance(distributionDO.getBalance());
                    balanceDetailDO.setBalanceDelta(0);
                    balanceDetailDO.setOrderNo(orderNo);
                    balanceDetailDO.setDescription(description);
                    balanceDetailDO.setGmtUpdate(now);
                    balanceDetailDO.setGmtCreate(now);
                    balanceDetailDO.setDistributionId(distributionId);
                    distributionBalanceDetailMapper.insert(balanceDetailDO);
                }
            }
            return distributionDO.getParentId();
        }
        return 0;
    }


    /**
     * 解冻门店金额
     *
     * @param delta
     * @param distributionId
     * @param orderNo
     * @param description
     */
    public void unfreezeBalance(Integer delta, Long distributionId, String orderNo, String description) throws ServiceException {
        Date now = new Date();
        DistributionDO distributionDO = distributionMapper.selectByIdForUpdate(distributionId);
        if (distributionDO != null) {
            if (distributionDO.getFreezeBalance() < delta) {
                throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_FREEZE_BALANCE_NOT_ENOUGH);
            }
            //DistributionBalanceDetailDO lastDetailDO = distributionBalanceDetailMapper.getDistributionUserLastForUpdate(distributionId);

            //更新操作
            if (delta != 0) {
                //更新主表 将钱解冻 从冻结余额中转化到余额中
                distributionMapper.unfreezeBalance(distributionId, delta);
                //更新明细表
                DistributionBalanceDetailDO balanceDetailDO = new DistributionBalanceDetailDO();
                balanceDetailDO.setFreezeBalance(distributionDO.getFreezeBalance() - delta);
                balanceDetailDO.setFreezeBalanceDelta(-delta);
                balanceDetailDO.setBalance(distributionDO.getBalance() + delta);
                balanceDetailDO.setBalanceDelta(delta);
                balanceDetailDO.setOrderNo(orderNo);
                balanceDetailDO.setDescription(description);
                balanceDetailDO.setGmtUpdate(now);
                balanceDetailDO.setGmtCreate(now);
                balanceDetailDO.setDistributionId(distributionDO.getId());
                distributionBalanceDetailMapper.insert(balanceDetailDO);
            }

        }
    }

    /**
     * 解冻用户金额
     * @param orderNo
     * @throws ServiceException
     */
    public void unfreezeOrder(String orderNo) throws ServiceException {
        List<DistributionBalanceDetailDO> distributionBalanceDetailDOList = distributionBalanceDetailMapper.selectList(new EntityWrapper<DistributionBalanceDetailDO>().eq("order_no", orderNo));
        if (!CollectionUtils.isEmpty(distributionBalanceDetailDOList)) {
            for (DistributionBalanceDetailDO detailDO : distributionBalanceDetailDOList) {
                if (detailDO.getFreezeBalanceDelta() >= 0) {
                    unfreezeBalance(detailDO.getFreezeBalanceDelta(), detailDO.getDistributionId(), orderNo, detailDO.getDescription().replace("冻结金额", "解冻金额"));
                } else {
                    throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_HAS_BEEN_UNFREEZE);
                }
            }
        }
    }

    /**
     * 订单退款
     *
     * @param orderNo
     * @throws ServiceException
     */
    public void refundOrder(String orderNo) throws ServiceException {
        List<DistributionBalanceDetailDO> distributionBalanceDetailDOList = distributionBalanceDetailMapper.selectList(new EntityWrapper<DistributionBalanceDetailDO>().eq("order_no", orderNo));
        if (!CollectionUtils.isEmpty(distributionBalanceDetailDOList)) {
            for (DistributionBalanceDetailDO detailDO : distributionBalanceDetailDOList) {
                if (detailDO.getFreezeBalanceDelta() >= 0) {
                    incFreezeBalance(-detailDO.getFreezeBalanceDelta(), detailDO.getDistributionId(), orderNo, detailDO.getDescription().replace("冻结金额", "退还金额"));
                } else {
                    throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_HAS_BEEN_UNFREEZE);
                }
            }
        }
    }

    /**
     * 获取用户余额
     *
     * @param userId
     * @return
     * @throws ServiceException
     */
    public Integer balance(Long userId) throws ServiceException {
        List<DistributionDO> distributionDOList = distributionMapper.selectList(new EntityWrapper<DistributionDO>().eq("user_id", userId));
        if (CollectionUtils.isEmpty(distributionDOList)) {
            throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_NOT_EXIST);
        }
        return distributionDOList.get(0).getBalance();
    }

    /**
     * 调用出一定要加事务
     * 为订单创建抵扣单，并返回抵扣单的Id
     *
     * @param deductionSum
     * @param userId
     * @return
     */
    public Long createDeduction(Integer deductionSum, Long userId) throws ServiceException {
        // 1.创建抵扣单
        Date now = new Date();
        DistributionDeductionDO distributionDeductionDO = new DistributionDeductionDO();
        distributionDeductionDO.setStatus(DistributionDeductionStatusType.WAIT_CONFIRM.getCode());
        distributionDeductionDO.setSum(deductionSum);
        distributionDeductionDO.setUserId(userId);
        distributionDeductionDO.setGmtUpdate(now);
        distributionDeductionDO.setGmtCreate(now);
        if (distributionDeductionMapper.insert(distributionDeductionDO) > 0) {
            // 2.冻结余额
            // 2.1.锁行，并校验表是否一致
            DistributionDO distributionDO = distributionMapper.selectByUserIdForUpdate(userId);
           /* DistributionBalanceDetailDO lastDetail = distributionBalanceDetailMapper.getDistributionUserLastForUpdate(distributionDO.getId());
            //判断两个数据是否一致
            if (!lastDetail.getFreezeBalance().equals(distributionDO.getFreezeBalance()) || !lastDetail.getBalance().equals(distributionDO.getBalance())) {
                throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_YOUR_DATA_NOT_CONSTANCY);
            }*/
            // 2.2.更新主表   余额减少 同时 冻结金额增加
            if (distributionMapper.freezeBalance(distributionDO.getId(), deductionSum) > 0) {
                // 2.3.创建明细单，将抵扣的
                DistributionBalanceDetailDO balanceDetailDO = new DistributionBalanceDetailDO();
                balanceDetailDO.setFreezeBalance(distributionDO.getFreezeBalance() + deductionSum);
                balanceDetailDO.setFreezeBalanceDelta(deductionSum);
                balanceDetailDO.setBalance(distributionDO.getBalance() - deductionSum);
                balanceDetailDO.setBalanceDelta(-deductionSum);
                balanceDetailDO.setOrderNo("");
                balanceDetailDO.setDescription("佣金购物抵扣-RMB" + deductionSum / 100.0);
                balanceDetailDO.setGmtUpdate(now);
                balanceDetailDO.setGmtCreate(now);
                balanceDetailDO.setDistributionId(distributionDO.getId());
                if (distributionBalanceDetailMapper.insert(balanceDetailDO) > 0) {
                    return distributionDeductionDO.getId();
                }
            }
        }
        throw new AppServiceException(ExceptionDefinition.APP_UNKNOWN_EXCEPTION);
    }

    /**
     * 退还用户抵扣佣金 (全额)
     *
     * @param deductionId
     * @return
     * @throws ServiceException
     */
    public void returnDeduction(Long deductionId, Integer sum, Long userId) throws ServiceException {
        DistributionDeductionDO distributionDeductionDO = distributionDeductionMapper.selectById(deductionId);
        if (distributionDeductionDO != null && distributionDeductionDO.getStatus() == DistributionDeductionStatusType.WAIT_CONFIRM.getCode()) {
            // 1.将抵扣单状态退回
            Date now = new Date();
            DistributionDeductionDO updateDeductionDO = new DistributionDeductionDO();
            updateDeductionDO.setId(deductionId);
            updateDeductionDO.setStatus(DistributionDeductionStatusType.RETURNED.getCode());
            updateDeductionDO.setGmtUpdate(now);
            if (distributionDeductionMapper.updateById(updateDeductionDO) > 0) {
                // 2.归还佣金
                // 2.1.锁行，并校验表是否一致
                DistributionDO distributionDO = distributionMapper.selectByUserIdForUpdate(userId);
                DistributionBalanceDetailDO lastDetail = distributionBalanceDetailMapper.getDistributionUserLastForUpdate(distributionDO.getId());
                //判断两个数据是否一致
                if (!lastDetail.getFreezeBalance().equals(distributionDO.getFreezeBalance()) || !lastDetail.getBalance().equals(distributionDO.getBalance())) {
                    throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_YOUR_DATA_NOT_CONSTANCY);
                }
                // 2.2.更新主表
                Integer deductionSum = distributionDeductionDO.getSum();
                if (sum != null) {
                    // 若sum存在
                    deductionSum = sum;
                }
                if (distributionMapper.unfreezeBalance(distributionDO.getId(), deductionSum) > 0) {
                    // 2.3 更新明细表
                    DistributionBalanceDetailDO balanceDetailDO = new DistributionBalanceDetailDO();
                    balanceDetailDO.setFreezeBalance(distributionDO.getFreezeBalance() - deductionSum);
                    balanceDetailDO.setFreezeBalanceDelta(-deductionSum);
                    balanceDetailDO.setBalance(distributionDO.getBalance() + deductionSum);
                    balanceDetailDO.setBalanceDelta(+deductionSum);
                    balanceDetailDO.setOrderNo("");
                    balanceDetailDO.setDescription("佣金购物抵扣(退款/取消)退还-RMB" + deductionSum / 100.0);
                    balanceDetailDO.setGmtUpdate(now);
                    balanceDetailDO.setGmtCreate(now);
                    balanceDetailDO.setDistributionId(distributionDO.getId());
                    if (distributionBalanceDetailMapper.insert(balanceDetailDO) > 0) {
                        return;
                    }
                }
            }
            throw new AppServiceException(ExceptionDefinition.APP_UNKNOWN_EXCEPTION);
        }
        throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_DEDUCTION_STATUS_INCORRECT);
    }

    /**
     * 确认用户抵扣佣金
     *
     * @param deductionId
     * @throws ServiceException
     */
    public void confirmDeduction(Long deductionId, Long userId) throws ServiceException {
        DistributionDeductionDO distributionDeductionDO = distributionDeductionMapper.selectById(deductionId);
        if (distributionDeductionDO != null && distributionDeductionDO.getStatus() == DistributionDeductionStatusType.WAIT_CONFIRM.getCode()) {
            // 1.将抵扣单确认 确认抵扣 将状态从待确认转化为已确认
            Date now = new Date();
            DistributionDeductionDO updateDeductionDO = new DistributionDeductionDO();
            updateDeductionDO.setId(deductionId);
            updateDeductionDO.setStatus(DistributionDeductionStatusType.CONFIRMED.getCode());
            updateDeductionDO.setGmtUpdate(now);
            if (distributionDeductionMapper.updateById(updateDeductionDO) > 0) {
                // 2.归还佣金
                // 2.1.锁行，并校验表是否一致
                DistributionDO distributionDO = distributionMapper.selectByUserIdForUpdate(userId);
                DistributionBalanceDetailDO lastDetail = distributionBalanceDetailMapper.getDistributionUserLastForUpdate(distributionDO.getId());
                //判断两个数据是否一致
                if (!lastDetail.getFreezeBalance().equals(distributionDO.getFreezeBalance()) || !lastDetail.getBalance().equals(distributionDO.getBalance())) {
                    throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_YOUR_DATA_NOT_CONSTANCY);
                }
                // 2.2.更新主表 将冻结金额减扣掉
                if (distributionMapper.decFreezeBalance(distributionDO.getId(), distributionDeductionDO.getSum()) > 0) {
                    // 2.3 更新明细表
                    DistributionBalanceDetailDO balanceDetailDO = new DistributionBalanceDetailDO();
                    Integer deductionSum = distributionDeductionDO.getSum();
                    balanceDetailDO.setFreezeBalance(distributionDO.getFreezeBalance() - deductionSum);
                    balanceDetailDO.setFreezeBalanceDelta(-deductionSum);
                    balanceDetailDO.setBalance(distributionDO.getBalance());
                    balanceDetailDO.setBalanceDelta(0);
                    balanceDetailDO.setOrderNo("");
                    balanceDetailDO.setDescription("购物抵扣-确认收货-RMB" + deductionSum / 100.0);
                    balanceDetailDO.setGmtUpdate(now);
                    balanceDetailDO.setGmtCreate(now);
                    balanceDetailDO.setDistributionId(distributionDO.getId());
                    if (distributionBalanceDetailMapper.insert(balanceDetailDO) > 0) {
                        return;
                    }
                }
            }
        }
        throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_DEDUCTION_STATUS_INCORRECT);
    }

    /**
     * 获取分销用户排行榜
     *
     * @param pageNo
     * @param pageSize
     * @return
     * @throws ServiceException
     */
    public Page<DistributionRankingDTO> getRankingPage(Integer pageNo, Integer pageSize) throws ServiceException {
        List<DistributionRankingDTO> list = distributionMapper.getDistributionRanking((pageNo - 1) * pageSize, pageSize);
        Integer count = distributionMapper.selectCount(null);
        return new Page<>(list, pageNo, pageSize, count);
    }

    /**
     * 获取分销核销订单
     *
     * @param pageNo
     * @param pageSize
     * @param distributionId
     * @return
     * @throws ServiceException
     */
    public Page<DistributionOrderDTO> getDistributionOrderPage(Integer pageNo, Integer pageSize, Long distributionId) throws ServiceException {
        List<DistributionOrderDTO> list = distributionBalanceDetailMapper.getDistributionOrder((pageNo - 1) * pageSize, pageSize, distributionId);
        Integer count = distributionBalanceDetailMapper.selectCount(
                new EntityWrapper<DistributionBalanceDetailDO>()
                        .eq("distribution_id", distributionId)
                        .gt("balance_delta", 0)
                        .ne("order_no", ""));
        return new Page<>(list, pageNo, pageSize, count);
    }

    /**
     * 获取推广的用户
     *
     * @param distributionId
     * @return
     * @throws ServiceException
     */
    public List<DistributionUserDTO> getDistributionUserPage(Long distributionId) throws ServiceException {
        // 通过select distinct userId 所有核销订单的用户Id。通过 select user in 来查找出所有用户即可。但是这样无法获取到该用户核销的总金额。
        // 由于订单里面没保存核销金额。所以若需要获取核销总金额，只能将该用户订单全部查出来（作为子查询），然后用in去明细表里面查。
        List<DistributionUserDTO> distributionUserIds = distributionMapper.getDistributionUser(distributionId);
        if (!CollectionUtils.isEmpty(distributionUserIds)) {
            // 封装用户信息
            distributionUserIds.forEach(item -> {
                UserDO userDO = userMapper.getUserNicknameAndAvartar(item.getUserId());
                item.setNickname(userDO.getNickname());
                item.setAvatarUrl(userDO.getAvatarUrl());
            });
        }
        return distributionUserIds;
    }


    /**
     * 获取用户余额
     *
     * @param userId
     * @return
     * @throws ServiceException
     */
    public Long getDistributionId(Long userId) throws ServiceException {
        List<DistributionDO> distributionDOList = distributionMapper.selectList(new EntityWrapper<DistributionDO>().eq("user_id", userId));
        if (CollectionUtils.isEmpty(distributionDOList)) {
            throw new AppServiceException(ExceptionDefinition.DISTRIBUTION_NOT_EXIST);
        }
        return distributionDOList.get(0).getId();
    }

}
